const startButton = document.getElementById("startButton");  
const stopButton = document.getElementById("stopButton");  
const audioPlayback = document.getElementById("audioPlayback");  
const statusMessage = document.getElementById("statusMessage");  
const sendTextButton = document.getElementById("sendTextButton");  
const textInput = document.getElementById("textInput");  
const chatBox = document.getElementById("chatBox");  

let recognizing = false;  
const socket = new WebSocket("ws://localhost:3000"); // 假设后端服务器地址  
let mediaRecorder; // 媒体录音器  
const BAIDU_API_URL = '1jpd6i4N2eG5V6FRiEY701VP'; // 百度语音识别API URL  
const ACCESS_TOKEN = 'https://aip.baidubce.com/oauth/2.0/token'; // 替换为你的API访问令牌  

// 处理语音识别部分  
startButton.onclick = async () => {  
    if (recognizing) return;  

    recognizing = true; // 设置为正在识别状态  
    statusMessage.style.display = 'block'; // 显示状态消息  
    startButton.style.display = 'none'; // 隐藏开始按钮  
    stopButton.style.display = 'block'; // 显示停止按钮  

    // 检查浏览器支持  
    if (!('MediaRecorder' in window)) {  
        alert('浏览器不支持音频录制 API');  
        return;  
    }  

    // 获取麦克风权限  
    const stream = await navigator.mediaDevices.getUserMedia({ audio: true });  
    mediaRecorder = new MediaRecorder(stream);  
    const audioChunks = [];  

    mediaRecorder.ondataavailable = event => {  
        audioChunks.push(event.data);  
    };  

    mediaRecorder.onstop = async () => {  
        const audioBlob = new Blob(audioChunks, { type: 'audio/wav' });  
        const audioUrl = URL.createObjectURL(audioBlob);  
        audioPlayback.src = audioUrl; // 更新音频控件的源  
        audioPlayback.play(); // 播放录制的音频  

        const arrayBuffer = await audioBlob.arrayBuffer(); // 获取录制的音频数据  
        const byteArray = new Uint8Array(arrayBuffer); // 将 ArrayBuffer 转换为字节数组  
        
        // 打印字节数据  
        console.log('发送的字节数据:', byteArray);  
        
        // 打印字节数据的十六进制表示  
        console.log('发送的字节数据（十六进制）:', Array.from(byteArray).map(b => b.toString(16).padStart(2, '0')).join(' '));  

        // 发送音频数据到百度语音识别API  
        const formData = new FormData();  
        formData.append('audio', audioBlob, 'audio.wav');  

        const response = await fetch(`${BAIDU_API_URL}?access_token=${ACCESS_TOKEN}`, {  
            method: 'POST',  
            body: formData  
        });  

        const result = await response.json(); // 解析API返回的结果  

        // 输出结果到控制台  
        console.log('百度返回的结果:', result);  
        
        // 处理返回的识别结果  
        if (result.err_no === 0) {  
            chatBox.innerHTML += `<div><strong>AI:</strong> ${result.result[0]}</div>`;  
        } else {  
            chatBox.innerHTML += `<div><strong>AI:</strong> 识别错误: ${result.err_msg}</div>`;  
        }  

        // 重置状态  
        recognizing = false;  
        statusMessage.style.display = 'none'; // 隐藏状态信息  
        startButton.style.display = 'block'; // 显示开始按钮  
        stopButton.style.display = 'none'; // 隐藏停止按钮  
    };  

    mediaRecorder.start(); // 开始录音  
};  

// 停止按钮点击事件  
stopButton.onclick = () => {  
    if (recognizing) {  
        mediaRecorder.stop(); // 停止录音  
        recognizing = false; // 更新状态  
    }  
};  

// 处理服务器返回的音频数据  
socket.onmessage = (event) => {  
    const response = new Blob([event.data], { type: 'audio/wav' });  
    const audioUrl = URL.createObjectURL(response);  
    audioPlayback.src = audioUrl;  
    audioPlayback.play();  
};  
// 处理文本聊天  
sendTextButton.onclick = async () => {  
    const userInput = textInput.value.trim();  
    if (userInput) {  
        chatBox.innerHTML += `<div><strong>你:</strong> ${userInput}</div>`;  
        textInput.value = ''; // 清空输入框  

        // 发送文本内容到服务器  
        const response = await fetch("http://localhost:3000/api/chat", {  
            method: 'POST',  
            headers: {  
                'Content-Type': 'application/json'  
            },  
            body: JSON.stringify({ message: userInput })  
        });  

        // 处理服务器返回的AI响应  
        const result = await response.json();  
        chatBox.innerHTML += `<div><strong>AI:</strong> ${result.reply}</div>`;  
        document.getElementById('sendTextButton').addEventListener('click', async () => {
            const userQuestion = document.getElementById('textInput').value;
            const resultDiv = document.getElementById('result');
        
            if (!userQuestion.trim()) {
                alert('请输入问题');
                return;
            }
        
            try {
                const answer = await getDeepLResponse(userQuestion);
                resultDiv.innerText = '回答: ' + answer;
           } catch (error) {
                console.error('发生错误:', error);
                resultDiv.innerText = '发生错误: ' + error.message;
           }
        });
    }  
};  